import relationalStore from '@ohos.data.relationalStore'
import common from '@ohos.app.ability.common'
import { ColumnInfo, ColumnType } from '../bean/ColumnInfo'
import Logger from './Logger'

const DB_FILENAME: string = 'HeiMaHealthy.db'
const CREATE_TABLE_SQL: string = `
 CREATE TABLE IF NOT EXISTS record (
   id INTEGER PRIMARY KEY AUTOINCREMENT,
   type_id INTEGER NOT NULL,
   item_id INTEGER NOT NULL,
   amount DOUBLE NOT NULL,
   create_time INTEGER NOT NULL
 )
 `
class DBUtil {
  rdbStore: relationalStore.RdbStore

  initDB(context: common.UIAbilityContext): Promise<void> {
    let config: relationalStore.StoreConfig = {
      name: DB_FILENAME,
      securityLevel: relationalStore.SecurityLevel.S1
    }

    return new Promise<void>((resolve, reject) => {
      relationalStore.getRdbStore(context, config)
        .then(rdbStore => {
          this.rdbStore = rdbStore
          console.log('rdbStore 初始化完成')
          // console.log('----')
          // this.createTable(CREATE_TABLE_SQL)
          resolve()
        })
        .catch(reason => {
          console.log('rdbStore 初始化异常', JSON.stringify(reason))
          reject(reason)
        })
    })
  }

  createTable(createSql: string): Promise<void> {
    console.log(createSql)
    return new Promise<void>((resolve, reject) => {
      console.log(createSql)
      this.rdbStore.executeSql(createSql)
        .then(() => {
          console.log('创建表成功', createSql)
          resolve()
        })
        .catch(err => {
          console.error('创建表失败,'+err.message, JSON.stringify(err) );
          reject(err)
        })
    })
  }

  insert(tableName: string, obj:any, columns: ColumnInfo[]): Promise<number> {
    return new Promise((resolve, reject) => {
      //构建新增数据结构
      let value = this.buildValueBucket(obj, columns)
      console.log(JSON.stringify(value))
      //执行新增
      this.rdbStore.insert(tableName, value, (err, id) => {
        if (err) {
          console.error('新增失败！失败原因：', JSON.stringify(err))
          reject(err)
        } else {
          console.log('新增成功！新增id：', id.toString())
          resolve(id)
        }
      })
    })
  }

  delete(predicates: relationalStore.RdbPredicates): Promise<number> {
    return new Promise((resolve, reject) => {
      //执行新增
      this.rdbStore.delete(predicates, (err, rows) => {
        if (err) {
          Logger.error('删除失败！失败原因：', JSON.stringify(err))
          reject(err)
        } else {
          Logger.debug('删除成功！删除行数：', rows.toString())
          resolve(rows)
        }
      })
    })
  }

  queryForList<T>(predicates: relationalStore.RdbPredicates, columns: ColumnInfo[]): Promise<T[]> {
    return new Promise((resolve, reject) => {
      //执行新增
      this.rdbStore.query(predicates, columns.map(info => info.columnName), (err, result) => {
        if (err) {
          Logger.error('查询失败！失败原因：', JSON.stringify(err))
          reject(err)
        } else {
          Logger.debug('查询成功！查询行数：', result.rowCount.toString())
          resolve(this.parseResultSet(result, columns))
        }
      })
    })
  }

  update(obj:any, predicates: relationalStore.RdbPredicates, columns: ColumnInfo[]): Promise<void> {
    return new Promise((resolve, reject) => {
      //构建新增数据结构
      let value = this.buildValueBucket(obj, columns)
      //执行新增
      this.rdbStore.update(value, predicates, (err, rows) => {
        if (err) {
          Logger.error('更新失败！失败原因：', JSON.stringify(err))
          reject(err)
        } else {
          Logger.debug('更新成功！更新rows：', rows.toString())
          resolve()
        }
      })
    })
  }

  // 把resultSet解析成json
  parseResultSet<T>(result: relationalStore.ResultSet, columns: ColumnInfo[]): T[] {
    let arr = []
    if(result.rowCount <= 0) return arr
    while (!result.isAtLastRow) {
      result.goToNextRow()
      let obj = {}
      columns.forEach(info => {
        let val = null
        switch (info.type) {
          case ColumnType.LONG:
            val = result.getLong(result.getColumnIndex(info.columnName))
            break
          case ColumnType.DOUBLE:
            val = result.getDouble(result.getColumnIndex(info.columnName))
            break
          case ColumnType.STRING:
            val = result.getString(result.getColumnIndex(info.columnName))
            break
          case ColumnType.BLOB:
            val = result.getBlob(result.getColumnIndex(info.columnName))
            break
        }
        obj[info.name] = val
      })
      arr.push(obj)
    }
    return arr
  }

  // 把传过来的数据结构，转换为rdb需要的bucket结构
  buildValueBucket(obj:any, columns:ColumnInfo[]): relationalStore.ValuesBucket {
    let value = {}
    columns.forEach(info => {
      let val = obj[info.name]
      if (typeof val !== 'undefined'){
        value[info.columnName] = val
      }
    })
    return value
  }
}
let dbUtil: DBUtil = new DBUtil()
export default dbUtil